import cgi
import os
import sys

from mod_python import apache, util

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','modules')))
import mods

from openid.store.sqlstore import PostgreSQLStore
from openid.consumer import consumer
from openid.extensions import sreg

dbConnection = mods.GetDBConnection()

def index(req):
	showForm = True
	web = mods.Web(req)

	error = False
	errorMessage = ''
	thisServer = "http://%s/" % (web.req.hostname)
	thisURL = '%sauth/index.py' % (thisServer)

	oidIdentifier = web.GetData('openid_identifier')
	oidIdentifierSafe = cgi.escape(oidIdentifier)
	oidStore = PostgreSQLStore(dbConnection)
	oidConsumer = consumer.Consumer(web.session, oidStore)

	#A new OpenID request
	if oidIdentifier:
		#Check if OID is valid
		try:
			oidAuthRequest = oidConsumer.begin(oidIdentifier)
		except:
			oidAuthRequest = None
			error = True
			errorMessage = "%s does not look like a valid OpenID service" % (oidIdentifierSafe)

		

		if oidAuthRequest:
			oidURL = oidAuthRequest.redirectURL(thisServer, thisURL, immediate=False)
			web.session.save()
			util.redirect(web.req, oidURL)

	#Check results to see if we can log in
	oidReturnArgs = {}
	if web.req.args:
		requestArgs = util.parse_qsl(web.req.args)
		for key, value in requestArgs:
			oidReturnArgs[key] = value.decode('utf-8')

		oidResponse = oidConsumer.complete(oidReturnArgs, thisURL)
		if oidResponse.status == consumer.SUCCESS:
			"""Do Login and create session"""
			web.userID = oidResponse.identity_url
			web.user = mods.User(oidResponse.identity_url)
			web.ReAuth()
			if web.user.name:
				web.Redirect("/index.py")
			else:
				web.Redirect("/auth/prefs.py")

	web.Header()

	if error:
		web.Write(errorMessage)
	if showForm:

		web.Write("""
	<br /><br />
	<script type="text/javascript" src="/includes/jquery.min.js"></script>
	<script type="text/javascript" src="/includes/jquery.openid.js"></script>

	<fieldset style="border: 0;">
		<form class="openid" method="post" action="/auth/index.py">
			<div><ul class="providers">

			<li class="openid" title="OpenID"><img src="/includes/images/openidW.png" alt="icon" />
				<span><strong>http://{your-openid-url}</strong></span></li>

			<li class="direct" title="Google">
				<img src="/includes/images/googleW.png" alt="icon" /><span>https://www.google.com/accounts/o8/id</span></li>

			<li class="direct" title="Yahoo">
				<img src="/includes/images/yahooW.png" alt="icon" /><span>http://yahoo.com/</span></li>

			<li class="username" title="MyOpenID user name">
				<img src="/includes/images/myopenidW.png" alt="icon" /><span>http://<strong>username</strong>.myopenid.com/</span></li>

			</ul></div>

			<fieldset style="border: 0;">
			<label for="openid_username">Enter your <span>Provider user name</span></label>
			<div><span></span><input type="text" name="openid_username" /><span></span>
			<input type="submit" value="Login" /></div>
			</fieldset>

			<fieldset style="border: 0;">
			<label for="openid_identifier">Enter your <a class="openid_logo" href="http://openid.net">OpenID</a></label>
			<div><input type="text" name="openid_identifier" />
			<input type="submit" value="Login" /></div>
			</fieldset>

		</form>
	</fieldset>

	<script type="text/javascript">  $(function() { $("form.openid:eq(0)").openid(); });</script>
	<br /><br />
	""")



	web.Footer()



